import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/sale_inquiry_form_odoo_api.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_form.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/sale_inquiry_form/sale_inquiry_partner_list.dart';
import '../../../generated/l10n.dart';

class SaleInquiryFormEdit extends StatefulWidget {
  SaleInquiryFormEdit({this.saleInquiryForm});

  final SaleInquiryForm? saleInquiryForm;

  @override
  _DmsDocumenttypeEditState createState() => _DmsDocumenttypeEditState();
}

class _DmsDocumenttypeEditState extends State<SaleInquiryFormEdit> {
  late SaleInquiryForm saleInquiryForm;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  List<SelectOptionVO> companyIdList = [];
  List<SelectOptionVO> deptIdList = [];
  List<SelectOptionVO> userIdList = [];
  List<SelectOptionVO> isTargetpriceList = [];
  String partnerTitle = '询价单位';
  ValueNotifier<num> total = ValueNotifier<num>(0);
  @override
  void initState() {
    super.initState();
    this.isAdd = widget.saleInquiryForm == null;
    this.saleInquiryForm = widget.saleInquiryForm ?? SaleInquiryForm();
    if (isAdd == true) {
      this.saleInquiryForm.taxRate = 13;
    }
    _loadSelectVO();
  }

  _loadSelectVO() async {
    deptIdList = await DynamicDataApi.getModelSelect(
        model: "hr.department",
        name: "complete_name",
        key: "department_code",
        operator: "in",
        val: ["HWB", "SC", "GGGGG", "PE", "SpT", "PG", "SpO"]);
    companyIdList = [
      SelectOptionVO(value: '', label: ""),
      SelectOptionVO(value: '3', label: "中天宽带技术有限公司"),
    ];
    isTargetpriceList = [
      SelectOptionVO(value: '', label: ""),
      SelectOptionVO(value: '0', label: "否"),
      SelectOptionVO(value: '1', label: "是"),
    ];
    if (isAdd == false) {
      userIdList = await DynamicDataApi.getUserSelect(
          val: int.parse(saleInquiryForm.deptId!));
    } else {
      saleInquiryForm.companyId = '3';
    }
    setState(() {});
  }

  selectProduct() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SaleInquiryPartnerList(partnerTitle: partnerTitle),
      ),
    ).then((v) {
      if (v != null) {
        formKey.currentState!.save();
        saleInquiryForm.partnerId = v['id'].toString();
        saleInquiryForm.partnerName = v['name'];

        saleInquiryForm.customerNature = v['customer_nature'] != false
            ? v['customer_nature'].toString()
            : '';
        saleInquiryForm.phone =
            v['phone'] != false ? v['phone'].toString() : '';
        saleInquiryForm.email = v['zip'] != false ? v['zip'].toString() : '';
        saleInquiryForm.arrivalPlace = v['customer_address']!=false?v['customer_address'].toString():'';
        setState(() {});
      }
    });
  }

  _getTotal() {
    total.value = 0;
    total.value = saleInquiryForm.trafficExpense! +
        saleInquiryForm.heatTreatment! +
        saleInquiryForm.letterOfCredit! +
        saleInquiryForm.commission! +
        saleInquiryForm.surveyReport! +
        saleInquiryForm.other! +
        saleInquiryForm.transportationInsurance! +
        saleInquiryForm.brokerageFee! +
        saleInquiryForm.experimentalExpenses! +
        saleInquiryForm.factoryInspection! +
        saleInquiryForm.creditInsurance! +
        saleInquiryForm.guaranteeFee! +
        saleInquiryForm.COOFG! +
        saleInquiryForm.notarialFees! +
        saleInquiryForm.financing! +
        saleInquiryForm.constructionServiceFee!;
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          // CrySelect(
          //   width: 300,
          //   label: '报价单位',
          //   dataList: companyIdList,
          //   value: saleInquiryForm.companyId,
          //   onSaved: (v) {
          //     saleInquiryForm.companyId = v;
          //   },
          //   validator: (v) {
          //     return v!.isEmpty ? S.of(context).required : null;
          //   },
          // ),
          CryInput(
            width: 325,
            label: '报价单位',
            value: '中天宽带技术有限公司',
          ),
          CrySelect(
            width: 325,
            label: '*事业部',
            dataList: deptIdList,
            value: saleInquiryForm.deptId,
            onSaved: (v) {
              saleInquiryForm.deptId = v;
            },
            onChange: (v) async {
              if (saleInquiryForm.deptId != v) {
                formKey.currentState!.save();
                saleInquiryForm.deptId = v;
                saleInquiryForm.userId = null;
                userIdList = [];
                try {
                  userIdList =
                      await DynamicDataApi.getUserSelect(val: int.parse(v));
                } catch (e) {
                  userIdList = [];
                }
                setState(() {});
              }
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 325,
            label: '*询价单编号',
            value: saleInquiryForm.inquiryNo,
            onSaved: (v) {
              saleInquiryForm.inquiryNo = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelect(
            width: 325,
            label: '*业务员',
            dataList: userIdList,
            value: saleInquiryForm.userId,
            onSaved: (v) {
              saleInquiryForm.userId = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 325,
            label: '*询价单位',
            value: saleInquiryForm.partnerName,
            onSaved: (v) {
              saleInquiryForm.partnerName = v;
            },
            onTap: () => selectProduct(),
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 325,
            label: '电话',
            enable: false,
            value: saleInquiryForm.phone,
            onSaved: (v) {
              saleInquiryForm.phone = v;
            },
          ),
          CryInput(
            width: 325,
            label: '客户性质',
            enable: false,
            value: saleInquiryForm.customerNature,
            onSaved: (v) {
              saleInquiryForm.customerNature = v;
            },
          ),
          CryInput(
            width: 325,
            label: '邮箱',
            enable: false,
            value: saleInquiryForm.email,
            onSaved: (v) {
              saleInquiryForm.email = v;
            },
          ),
          CryInput(
            width: 325,
            label: '到货地点',
            enable: false,
            value: saleInquiryForm.arrivalPlace,
            onSaved: (v) {
              saleInquiryForm.arrivalPlace = v;
            },
          ),
          CryInput(
            width: 325,
            label: '*付费方式',
            value: saleInquiryForm.paymentMethod,
            onSaved: (v) {
              saleInquiryForm.paymentMethod = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            width: 325,
            label: '*项目名称',
            value: saleInquiryForm.projectName,
            onSaved: (v) {
              saleInquiryForm.projectName = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CrySelect(
            width: 325,
            label: '是否有目标价',
            dataList: isTargetpriceList,
            value: saleInquiryForm.isTargetprice,
            onSaved: (v) {
              saleInquiryForm.isTargetprice = v;
            },
          ),

          // 新增字段开始；
          CryInput(
            width: 325,
            label: '报价币种',
            value: saleInquiryForm.currency,
            onSaved: (v) {
              saleInquiryForm.currency = v;
            },
          ),
          CryInputNum(
            width: 325,
            label: '下单汇率',
            value: saleInquiryForm.exchangeRate,
            onSaved: (v) {
              saleInquiryForm.exchangeRate = v;
            },
          ),
          CryInputNum(
            width: 325,
            label: '税率%',
            value: saleInquiryForm.taxRate,
            onSaved: (v) {
              saleInquiryForm.taxRate = v;
            },
          ),
          CryInputNum(
            width: 325,
            label: '利润率%',
            value: saleInquiryForm.profitMargin,
            onSaved: (v) {
              saleInquiryForm.profitMargin = v;
            },
          ),

          CryInputNum(
            width: 325,
            label: '运输费用（元）',
            value: saleInquiryForm.trafficExpense,
            onSaved: (v) {
              saleInquiryForm.trafficExpense = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          CryInputNum(
            width: 325,
            label: '信用证费用（元）',
            value: saleInquiryForm.letterOfCredit,
            onSaved: (v) {
              saleInquiryForm.letterOfCredit = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          CryInputNum(
            width: 325,
            label: '海运费/空运费（元）',
            value: saleInquiryForm.oceanFreight,
            onSaved: (v) {
              saleInquiryForm.oceanFreight = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          CryInputNum(
            width: 325,
            label: '运输保险（元）',
            value: saleInquiryForm.transportationInsurance,
            onSaved: (v) {
              saleInquiryForm.transportationInsurance = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          CryInputNum(
            width: 325,
            label: '保函费用（元）',
            value: saleInquiryForm.guaranteeFee,
            onSaved: (v) {
              saleInquiryForm.guaranteeFee = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          CryInputNum(
            width: 325,
            label: '熏蒸/热处理费（元）',
            value: saleInquiryForm.heatTreatment,
            onSaved: (v) {
              saleInquiryForm.heatTreatment = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          CryInputNum(
            width: 325,
            label: '报检代理费（元）',
            value: saleInquiryForm.brokerageFee,
            onSaved: (v) {
              saleInquiryForm.brokerageFee = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          CryInputNum(
            width: 325,
            label: '普惠制产地证（元）',
            value: saleInquiryForm.COOFG,
            onSaved: (v) {
              saleInquiryForm.COOFG = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '试验费（元）',
            value: saleInquiryForm.experimentalExpenses,
            onSaved: (v) {
              saleInquiryForm.experimentalExpenses = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '认证、公证费（元）',
            value: saleInquiryForm.notarialFees,
            onSaved: (v) {
              saleInquiryForm.notarialFees = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '佣金（元）',
            value: saleInquiryForm.commission,
            onSaved: (v) {
              saleInquiryForm.commission = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '厂验（元）',
            value: saleInquiryForm.factoryInspection,
            onSaved: (v) {
              saleInquiryForm.factoryInspection = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '融资费用（元）',
            value: saleInquiryForm.financing,
            onSaved: (v) {
              saleInquiryForm.financing = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '信用保险（元）',
            value: saleInquiryForm.creditInsurance,
            onSaved: (v) {
              saleInquiryForm.creditInsurance = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '施工服务费（元）',
            value: saleInquiryForm.constructionServiceFee,
            onSaved: (v) {
              saleInquiryForm.constructionServiceFee = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '其他费（元）',
            value: saleInquiryForm.other,
            onSaved: (v) {
              saleInquiryForm.other = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),

          CryInputNum(
            width: 325,
            label: '资信调查报告费（元）',
            value: saleInquiryForm.surveyReport,
            onSaved: (v) {
              saleInquiryForm.surveyReport = v;
            },
            onChange: (v) {
              formKey.currentState?.save();
              _getTotal();
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          ValueListenableBuilder<num>(
            valueListenable: total,
            builder: (context, value, child) {
              return CryInputNum(
                width: 325,
                label: '费用合计（元）',
                enable: false,
                value: total.value,
                onSaved: (v) {
                  saleInquiryForm.amountTotal = v;
                },
              );
            },
          ),
          CryInputNum(
            width: 325,
            label: '毛利润（元）',
            value: saleInquiryForm.grossProfit,
            onSaved: (v) {
              saleInquiryForm.grossProfit = v;
            },
            // validator: (v) {
            //   return v!.isEmpty ? S.of(context).required : null;
            // },
          ),
          // 新增字段结束；

          CryInput(
            label: '产品描述',
            value: saleInquiryForm.content,
            onSaved: (v) {
              saleInquiryForm.content = v;
            },
          ),
          CryInput(
            label: '备注',
            value: saleInquiryForm.comment,
            onSaved: (v) {
              saleInquiryForm.comment = v;
            },
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            saleInquiryForm.state = '0';
            form.save();
            SaleInquiryFormOdooApi.saveOrUpdate(saleInquiryForm.toOdooMap())
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
